{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 字符串分割\n",
        "\n",
        "本教程介绍Pandas中字符串分割的相关知识点和代码案例，包括`str.split()`、`str.rsplit()`、`str.partition()`和`str.rpartition()`方法的使用。\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 学习目标\n",
        "\n",
        "- 掌握`str.split()`方法分割字符串\n",
        "- 掌握`str.rsplit()`方法从右侧分割字符串\n",
        "- 掌握`str.partition()`方法分割为三部分\n",
        "- 掌握`str.rpartition()`方法从右侧分割为三部分\n",
        "- 了解分割参数的使用（分隔符、最大分割次数、展开等）\n",
        "- 学习实际应用案例\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. 导入库\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. str.split() - 分割字符串\n",
        "\n",
        "`str.split()`方法用于将Series中每个字符串按照指定的分隔符分割成列表。\n",
        "\n",
        "### 语法\n",
        "```python\n",
        "series.str.split(pat=None, n=-1, expand=False)\n",
        "```\n",
        "\n",
        "### 参数\n",
        "- `pat`: 分隔符（字符串或正则表达式），默认为None（按空白字符分割）\n",
        "- `n`: 最大分割次数，默认为-1（不限制）\n",
        "- `expand`: 是否展开为DataFrame，默认为False（返回Series of lists）\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.1 基本用法\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['Python,Programming,Data', 'Pandas,Analysis,Science', 'NumPy,Arrays,Math'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 按逗号分割\n",
        "print(\"\\n按逗号分割:\")\n",
        "result = data.str.split(',')\n",
        "print(result)\n",
        "print(\"\\n类型:\", type(result.iloc[0]))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.2 按空白字符分割（默认）\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建包含空格的字符串\n",
        "data = pd.Series(['Python Programming Data', 'Pandas Analysis Science', 'NumPy Arrays Math'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 按空白字符分割（默认）\n",
        "print(\"\\n按空白字符分割（默认）:\")\n",
        "result = data.str.split()\n",
        "print(result)\n",
        "\n",
        "# 也可以显式指定\n",
        "result2 = data.str.split(pat=None)\n",
        "print(\"\\n显式指定pat=None:\")\n",
        "print(result2)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.3 限制分割次数（n参数）\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['a,b,c,d,e', '1,2,3,4,5', 'x,y,z'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 不限制分割次数（默认）\n",
        "print(\"\\n不限制分割次数:\")\n",
        "print(data.str.split(','))\n",
        "\n",
        "# 限制分割1次（分割成2部分）\n",
        "print(\"\\n限制分割1次（n=1）:\")\n",
        "print(data.str.split(',', n=1))\n",
        "\n",
        "# 限制分割2次（分割成3部分）\n",
        "print(\"\\n限制分割2次（n=2）:\")\n",
        "print(data.str.split(',', n=2))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.4 展开为DataFrame（expand参数）\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['John,Doe,30', 'Jane,Smith,25', 'Bob,Johnson,35'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 不展开（返回Series of lists）\n",
        "print(\"\\n不展开（expand=False）:\")\n",
        "result = data.str.split(',', expand=False)\n",
        "print(result)\n",
        "print(\"类型:\", type(result.iloc[0]))\n",
        "\n",
        "# 展开为DataFrame\n",
        "print(\"\\n展开为DataFrame（expand=True）:\")\n",
        "result_df = data.str.split(',', expand=True)\n",
        "print(result_df)\n",
        "print(\"类型:\", type(result_df))\n",
        "print(\"\\n列名:\", result_df.columns.tolist())\n",
        "\n",
        "# 可以指定列名\n",
        "result_df.columns = ['First Name', 'Last Name', 'Age']\n",
        "print(\"\\n指定列名后:\")\n",
        "print(result_df)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.5 使用正则表达式分割\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['Python,Programming;Data', 'Pandas,Analysis;Science', 'NumPy,Arrays;Math'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 使用正则表达式分割（按逗号或分号）\n",
        "print(\"\\n使用正则表达式分割（按逗号或分号）:\")\n",
        "result = data.str.split(r'[,;]', regex=True)\n",
        "print(result)\n",
        "\n",
        "# 展开为DataFrame\n",
        "print(\"\\n展开为DataFrame:\")\n",
        "result_df = data.str.split(r'[,;]', regex=True, expand=True)\n",
        "print(result_df)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 2.6 处理NaN值\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 包含NaN的数据\n",
        "data = pd.Series(['a,b,c', 'x,y,z', np.nan, '1,2,3', None])\n",
        "print(\"包含NaN的数据:\")\n",
        "print(data)\n",
        "\n",
        "# 分割时NaN返回NaN\n",
        "result = data.str.split(',')\n",
        "print(\"\\n分割结果（NaN返回NaN）:\")\n",
        "print(result)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. str.rsplit() - 从右侧分割字符串\n",
        "\n",
        "`str.rsplit()`方法与`str.split()`类似，但从右侧（末尾）开始分割。\n",
        "\n",
        "### 语法\n",
        "```python\n",
        "series.str.rsplit(pat=None, n=-1, expand=False)\n",
        "```\n",
        "\n",
        "### 参数\n",
        "- `pat`: 分隔符（字符串或正则表达式），默认为None\n",
        "- `n`: 最大分割次数，默认为-1（不限制）\n",
        "- `expand`: 是否展开为DataFrame，默认为False\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 3.1 基本用法\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['a,b,c,d', '1,2,3,4', 'x,y,z'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 使用split()从左侧分割\n",
        "print(\"\\n使用split()从左侧分割:\")\n",
        "print(data.str.split(','))\n",
        "\n",
        "# 使用rsplit()从右侧分割（不限制次数时结果相同）\n",
        "print(\"\\n使用rsplit()从右侧分割（不限制次数）:\")\n",
        "print(data.str.rsplit(','))\n",
        "\n",
        "# 限制分割次数时，区别明显\n",
        "print(\"\\n限制分割1次:\")\n",
        "print(\"split()从左侧:\", data.str.split(',', n=1).tolist())\n",
        "print(\"rsplit()从右侧:\", data.str.rsplit(',', n=1).tolist())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 3.2 实际应用：提取文件名和扩展名\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建文件路径数据\n",
        "files = pd.Series(['document.pdf', 'image.jpg', 'data.xlsx', 'script.py'])\n",
        "print(\"文件名:\")\n",
        "print(files)\n",
        "\n",
        "# 使用rsplit()从右侧分割，提取文件名和扩展名\n",
        "result = files.str.rsplit('.', n=1, expand=True)\n",
        "result.columns = ['filename', 'extension']\n",
        "print(\"\\n分割结果:\")\n",
        "print(result)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. str.partition() - 分割为三部分\n",
        "\n",
        "`str.partition()`方法将字符串按照第一个出现的分隔符分割为三部分：分隔符之前、分隔符本身、分隔符之后。\n",
        "\n",
        "### 语法\n",
        "```python\n",
        "series.str.partition(sep=' ', expand=True)\n",
        "```\n",
        "\n",
        "### 参数\n",
        "- `sep`: 分隔符，默认为空格\n",
        "- `expand`: 是否展开为DataFrame，默认为True\n",
        "\n",
        "### 返回值\n",
        "- 返回包含三列的DataFrame：分隔符之前、分隔符、分隔符之后\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['Python Programming', 'Data Science', 'Machine Learning'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 使用partition()分割（按空格）\n",
        "result = data.str.partition(' ')\n",
        "print(\"\\n使用partition()分割（按空格）:\")\n",
        "print(result)\n",
        "print(\"\\n列名:\", result.columns.tolist())\n",
        "\n",
        "# 如果找不到分隔符，返回原字符串、空字符串、空字符串\n",
        "data2 = pd.Series(['Python', 'Data Science', 'Machine'])\n",
        "result2 = data2.str.partition(' ')\n",
        "print(\"\\n包含无空格字符串的情况:\")\n",
        "print(result2)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 4.1 使用其他分隔符\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建邮箱数据\n",
        "emails = pd.Series(['alice@example.com', 'bob@test.com', 'charlie@gmail.com'])\n",
        "print(\"邮箱地址:\")\n",
        "print(emails)\n",
        "\n",
        "# 使用partition()按@分割\n",
        "result = emails.str.partition('@')\n",
        "result.columns = ['username', 'separator', 'domain']\n",
        "print(\"\\n分割结果:\")\n",
        "print(result)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. str.rpartition() - 从右侧分割为三部分\n",
        "\n",
        "`str.rpartition()`方法从右侧（末尾）开始查找分隔符，将字符串分割为三部分。\n",
        "\n",
        "### 语法\n",
        "```python\n",
        "series.str.rpartition(sep=' ', expand=True)\n",
        "```\n",
        "\n",
        "### 参数\n",
        "- `sep`: 分隔符，默认为空格\n",
        "- `expand`: 是否展开为DataFrame，默认为True\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['Python Programming Data', 'Machine Learning AI', 'Data Science Analysis'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 使用partition()从左侧分割\n",
        "print(\"\\n使用partition()从左侧分割:\")\n",
        "result1 = data.str.partition(' ')\n",
        "print(result1)\n",
        "\n",
        "# 使用rpartition()从右侧分割\n",
        "print(\"\\n使用rpartition()从右侧分割:\")\n",
        "result2 = data.str.rpartition(' ')\n",
        "print(result2)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 5.1 实际应用：提取文件扩展名\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建文件路径数据（可能包含多个点）\n",
        "files = pd.Series(['my.document.pdf', 'image.file.jpg', 'data.backup.xlsx'])\n",
        "print(\"文件名:\")\n",
        "print(files)\n",
        "\n",
        "# 使用rpartition()从右侧分割，提取扩展名\n",
        "result = files.str.rpartition('.')\n",
        "result.columns = ['filename', 'separator', 'extension']\n",
        "print(\"\\n分割结果:\")\n",
        "print(result)\n",
        "print(\"\\n提取扩展名:\")\n",
        "print(result['extension'])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 6. 方法对比总结\n",
        "\n",
        "| 方法 | 功能 | 分割方向 | 返回结果 | 适用场景 |\n",
        "|------|------|---------|---------|---------|\n",
        "| `str.split()` | 分割字符串 | 从左到右 | Series of lists 或 DataFrame | 一般分割，需要多个部分 |\n",
        "| `str.rsplit()` | 分割字符串 | 从右到左 | Series of lists 或 DataFrame | 从末尾分割，如提取扩展名 |\n",
        "| `str.partition()` | 分割为三部分 | 从左到右 | DataFrame（3列） | 只需要分割一次，需要分隔符 |\n",
        "| `str.rpartition()` | 分割为三部分 | 从右到左 | DataFrame（3列） | 从末尾分割一次，需要分隔符 |\n",
        "\n",
        "### 选择建议\n",
        "\n",
        "- **需要多个部分**: 使用`split()`或`rsplit()`\n",
        "- **只需要三部分（包含分隔符）**: 使用`partition()`或`rpartition()`\n",
        "- **从末尾分割**: 使用`rsplit()`或`rpartition()`\n",
        "- **需要展开为DataFrame**: 设置`expand=True`\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 7. 实际应用案例\n",
        "\n",
        "### 7.1 解析姓名：分离姓和名\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建姓名数据\n",
        "names = pd.DataFrame({\n",
        "    'full_name': ['John Doe', 'Jane Smith', 'Bob Johnson', 'Mary Jane Watson']\n",
        "})\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(names)\n",
        "\n",
        "# 使用split()分割姓名\n",
        "name_parts = names['full_name'].str.split(' ', n=1, expand=True)\n",
        "name_parts.columns = ['first_name', 'last_name']\n",
        "names = pd.concat([names, name_parts], axis=1)\n",
        "\n",
        "print(\"\\n分割结果:\")\n",
        "print(names)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 7.2 解析地址：分离省市区\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建地址数据\n",
        "addresses = pd.DataFrame({\n",
        "    'address': [\n",
        "        '北京市,朝阳区,建国路88号',\n",
        "        '上海市,浦东新区,陆家嘴环路1000号',\n",
        "        '广州市,天河区,天河路123号'\n",
        "    ]\n",
        "})\n",
        "\n",
        "print(\"原始地址数据:\")\n",
        "print(addresses)\n",
        "\n",
        "# 使用split()分割地址\n",
        "address_parts = addresses['address'].str.split(',', expand=True)\n",
        "address_parts.columns = ['省/市', '区', '详细地址']\n",
        "addresses = pd.concat([addresses, address_parts], axis=1)\n",
        "\n",
        "print(\"\\n分割结果:\")\n",
        "print(addresses)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 7.3 解析URL：提取域名和路径\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建URL数据\n",
        "urls = pd.DataFrame({\n",
        "    'url': [\n",
        "        'https://www.example.com/path/to/page',\n",
        "        'http://www.test.com/index.html',\n",
        "        'https://www.demo.com/products/item123'\n",
        "    ]\n",
        "})\n",
        "\n",
        "print(\"原始URL数据:\")\n",
        "print(urls)\n",
        "\n",
        "# 使用partition()分割URL\n",
        "# 先按'://'分割，提取协议和剩余部分\n",
        "protocol_parts = urls['url'].str.partition('://')\n",
        "protocol_parts.columns = ['protocol', 'separator1', 'rest']\n",
        "\n",
        "# 再从剩余部分按'/'分割，提取域名和路径\n",
        "domain_parts = protocol_parts['rest'].str.split('/', n=1, expand=True)\n",
        "domain_parts.columns = ['domain', 'path']\n",
        "\n",
        "# 合并结果\n",
        "urls['protocol'] = protocol_parts['protocol']\n",
        "urls['domain'] = domain_parts['domain']\n",
        "urls['path'] = domain_parts['path'].fillna('')\n",
        "\n",
        "print(\"\\n解析结果:\")\n",
        "print(urls[['url', 'protocol', 'domain', 'path']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 7.4 解析CSV格式的标签\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建包含标签的数据\n",
        "articles = pd.DataFrame({\n",
        "    'title': ['Python Tutorial', 'Data Science Guide', 'Machine Learning Basics'],\n",
        "    'tags': ['python,programming,tutorial', 'data,science,analysis', 'ml,ai,learning']\n",
        "})\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(articles)\n",
        "\n",
        "# 分割标签\n",
        "articles['tag_list'] = articles['tags'].str.split(',')\n",
        "\n",
        "# 展开标签为多列（假设最多5个标签）\n",
        "tag_df = articles['tags'].str.split(',', expand=True)\n",
        "tag_df.columns = [f'tag_{i+1}' for i in range(tag_df.shape[1])]\n",
        "\n",
        "articles = pd.concat([articles, tag_df], axis=1)\n",
        "\n",
        "print(\"\\n分割结果:\")\n",
        "print(articles)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 7.5 提取文件信息\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建文件路径数据\n",
        "files = pd.DataFrame({\n",
        "    'filepath': [\n",
        "        '/home/user/documents/report.pdf',\n",
        "        '/home/user/images/photo.jpg',\n",
        "        '/home/user/data/analysis.xlsx',\n",
        "        'C:\\\\Users\\\\Documents\\\\file.txt'\n",
        "    ]\n",
        "})\n",
        "\n",
        "print(\"文件路径数据:\")\n",
        "print(files)\n",
        "\n",
        "# 提取文件名和扩展名\n",
        "# 先按路径分隔符分割\n",
        "files['filename_with_ext'] = files['filepath'].str.rsplit('/', n=1).str[-1]\n",
        "files['filename_with_ext'] = files['filename_with_ext'].str.rsplit('\\\\', n=1).str[-1]\n",
        "\n",
        "# 再提取文件名和扩展名\n",
        "name_ext = files['filename_with_ext'].str.rsplit('.', n=1, expand=True)\n",
        "name_ext.columns = ['filename', 'extension']\n",
        "files = pd.concat([files, name_ext], axis=1)\n",
        "\n",
        "print(\"\\n提取结果:\")\n",
        "print(files[['filepath', 'filename', 'extension']])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 8. 注意事项和最佳实践\n",
        "\n",
        "### 8.1 split() vs partition()的选择\n",
        "\n",
        "- **split()**: 适合需要多个部分的情况，可以控制分割次数\n",
        "- **partition()**: 适合只需要三部分（包含分隔符）的情况，固定返回3列\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 对比split()和partition()\n",
        "data = pd.Series(['a,b,c,d'])\n",
        "\n",
        "# 使用split()，可以控制分割次数\n",
        "print(\"使用split()，限制分割1次:\")\n",
        "print(data.str.split(',', n=1, expand=True))\n",
        "\n",
        "# 使用partition()，固定返回3列\n",
        "print(\"\\n使用partition()，固定返回3列:\")\n",
        "print(data.str.partition(','))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 8.2 处理分割后访问元素\n",
        "\n",
        "分割后返回的是Series of lists，访问元素需要使用索引。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 创建示例数据\n",
        "data = pd.Series(['a,b,c', 'x,y,z', '1,2,3'])\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 分割后访问元素\n",
        "result = data.str.split(',')\n",
        "print(\"\\n分割结果:\")\n",
        "print(result)\n",
        "\n",
        "# 访问第一个元素（每个列表的第一个元素）\n",
        "print(\"\\n访问第一个元素:\")\n",
        "print(result.str[0])\n",
        "\n",
        "# 访问最后一个元素\n",
        "print(\"\\n访问最后一个元素:\")\n",
        "print(result.str[-1])\n",
        "\n",
        "# 或者使用expand=True后直接访问列\n",
        "result_df = data.str.split(',', expand=True)\n",
        "print(\"\\n展开后访问第一列:\")\n",
        "print(result_df[0])\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 8.3 链式操作\n",
        "\n",
        "分割方法可以与其他字符串方法链式使用。\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 链式操作示例\n",
        "data = pd.Series(['  Python,Programming,Data  ', '  PANDAS,Analysis,Science  '])\n",
        "\n",
        "print(\"原始数据:\")\n",
        "print(data)\n",
        "\n",
        "# 链式操作：去除空白 -> 转小写 -> 分割\n",
        "result = data.str.strip().str.lower().str.split(',')\n",
        "print(\"\\n链式操作结果（去除空白 -> 转小写 -> 分割）:\")\n",
        "print(result)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 9. 总结\n",
        "\n",
        "### 9.1 关键要点\n",
        "\n",
        "1. **str.split()**: 从左到右分割字符串，返回Series of lists或DataFrame\n",
        "   - 可以控制分割次数（n参数）\n",
        "   - 可以展开为DataFrame（expand=True）\n",
        "   - 支持正则表达式\n",
        "\n",
        "2. **str.rsplit()**: 从右到左分割字符串，功能与split()类似\n",
        "   - 适合从末尾分割的场景，如提取文件扩展名\n",
        "\n",
        "3. **str.partition()**: 从左到右分割为三部分（分隔符前、分隔符、分隔符后）\n",
        "   - 固定返回3列的DataFrame\n",
        "   - 适合只需要分割一次的场景\n",
        "\n",
        "4. **str.rpartition()**: 从右到左分割为三部分\n",
        "   - 适合从末尾分割一次的场景\n",
        "\n",
        "### 9.2 应用场景\n",
        "\n",
        "- **数据解析**: 解析姓名、地址、URL等结构化数据\n",
        "- **文件处理**: 提取文件名、扩展名、路径信息\n",
        "- **标签处理**: 分割和展开标签列表\n",
        "- **数据清洗**: 分离和重组字符串数据\n",
        "\n",
        "### 9.3 最佳实践\n",
        "\n",
        "- 需要多个部分时使用`split()`或`rsplit()`\n",
        "- 只需要三部分时使用`partition()`或`rpartition()`\n",
        "- 从末尾分割时使用`rsplit()`或`rpartition()`\n",
        "- 需要DataFrame时设置`expand=True`\n",
        "- 使用链式操作简化代码\n",
        "- 注意处理NaN值和空字符串\n",
        "\n",
        "### 9.4 下一步学习\n",
        "\n",
        "掌握了字符串分割后，可以继续学习：\n",
        "- 字符串拼接（str.cat, str.join）\n",
        "- 字符串替换\n",
        "- 字符串格式化\n",
        "- 更多字符串操作方法\n"
      ]
    }
  ],
  "metadata": {
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
